import axios from 'axios'
import Qs from 'qs'
import Vue from 'vue'
import router from './router'

// 创建axios实例
export const http = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  method: 'POST',
  timeout: 10000, // 请求超时时间
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: (req) => {
    req = Qs.stringify(req)
    return req
  },
  transformResponse: (res) => {
    if (typeof res === 'string') {
      res = JSON.parse(res)
    }
    return res
  }
})
const MessageVue = new Vue()
// res拦截器
http.interceptors.response.use((res) => {
  return res.data
}, (error) => {
  const res = JSON.parse(error.request.response)
  if (res.status === 403) {
    router.push('/login')
    return false
  } else if (res.status === 500 && res.message) {
    MessageVue.$message.error({
      title: '失败',
      message: res.message
    })
  }
  return Promise.reject(error)
})

Vue.prototype.$http = http
